# -*- coding: utf-8 -*-
# @Author : zhaochen
# @Date   : 2019/4/13
# @File   : TX11_IncomeTaxGrowthRate.py
# @E-mail : zhaochen@bbdservice.com


'''eof
name:所得税增长率
code:TX11_IncomeTaxGrowthRate
tableName:
columnName:
groups:税务模块
dependencies:TX_CQ_DSJ
type:常用指标
datasourceType:在线指标
description:
eof'''

import sys
import re
import datetime
reload(sys)
sys.setdefaultencoding('utf-8')

null_type_list = ['', ' ', None, 'null', 'Null', 'NULL', '/', '-', '--']

def getTable(table_Name):
    '''
    获取表; 注意接口名称 为 TX_CQ_DSJ
    '''
    try:
        ic_data = TX_CQ_DSJ['data'].get(table_Name)
        if ic_data in null_type_list:
            return None
        else:
            return ic_data if isinstance(ic_data, list) and len(ic_data) > 0 else [{}]
    except:
        return None

def isfloat(x):
    '''
    判断x为float类型
    :param x:
    :return:
    '''
    try:
        if isinstance(float(x), float):
            if str(x) in ['inf', 'infinity', 'INF', 'INFINITY', 'True', 'NAN', 'nan',
                     'False', '-inf', '-INF', '-INFINITY', '-infinity', 'NaN', 'Nan']:
                return False
            else:
                return True
        else:
            return False
    except:
        return False

def formatDate(time):

    import re
    import datetime
    try:
        r = re.compile(r'\D')
        tmp = r.sub('', time)
        if tmp.isdigit():
            date = datetime.datetime.strptime(tmp, '%Y%m%d').strftime('%Y%m%d')
            return date
        else:
            return None
    except:
        return None

def TX11_IncomeTaxGrowthRate_SC():
    try:
        syptQysdsNd = getTable('syptQysdsNd')
        # 至少有两条数据才能求比率
        if syptQysdsNd is None or len(syptQysdsNd) < 2:
            return u'缺失值'
        else:
            flag = []
            resultDict = {}
            for i  in syptQysdsNd:
                if isfloat(i.get('ND')) and isfloat(i.get('YNSDSE')):
                    nd = i.get('ND')
                    se = float(i.get('YNSDSE'))
                    resultDict.update({nd: se})
                else:
                    flag.append(None)
            # 满足要求的数据少于2条，不能计算比率
            if len(resultDict) < 2 or len(flag) == len(syptQysdsNd):
                return u'缺失值'
            else:
                sortedKey = sorted(resultDict, reverse=True)
                # 最近那条记录
                result1 = resultDict.get(sortedKey[0])
                # 最远那条记录
                result2 = resultDict.get(sortedKey[-1])
                months = (float(sortedKey[0]) - float(sortedKey[-1])) * 12
                if result2 == 0:
                    return u'缺失值'
                else:
                    result = (result1 / result2 - 1) / months
                    return round(result, 4)
    except:
        return u'缺失值'

result = TX11_IncomeTaxGrowthRate_SC()